import {
	config
} from '../config/index'
// 封装微信请求方法

const doRequest = (params) => {
	let url = params.url;
	let data = params.data;
	let method = params.method;
	let header = {
		"Content-Type": "application/json"
	};
	// 鉴权验证，获取登录之后后端返回的token，存在即在头部Authorization写token，具体的看后端需求
	const token = wx.getStorageSync("token")
	if (token) {
		header.Authorization = `Bearer ${token}`;
	}
	const requestUrl = url.indexOf('https://') === -1 ? config.baseUrl + url : url;
	return new Promise((resolve, reject) => {
		wx.request({
			url: requestUrl,
			method: method,
			data: data,
			header: header,
			success(res) {
				// 判断状态码---errCode状态根据后端定义来判断
				const statusCode = res.data.code ? res.data.code : res.data.Code;
				switch (statusCode) {
					case 200:
						resolve(res.data.data);
						break;
					case 400:
						wx.showToast({
							title: `操作失败：${res.data.message}`,
							duration: 2000,
							icon: 'none'
						});
						reject(res.data.data);
						break;
					case 401:
						//移除以前保存的登录token信息
						wx.removeStorageSync('token');
						wx.showModal({
							title: "提示",
							content: "请登录",
							success(res) {
								if (res.confirm) {
									wx.navigateTo({
										url: "/pages/login/index",
									});
								}
							},
						});
						reject(res.data);
						break;
					default:
						// 其他异常
						wx.showToast({
							title: `接口请求失败`,
							duration: 2000,
							icon: 'none'
						});
						reject(res);
				}
			},
			fail(err) {
				if (err.errMsg.indexOf('request:fail') !== -1) {
					wx.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					});
				} else {
					wx.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);
			},
			complete() {
				wx.hideLoading()
			},
		});
	});
};
const request = {
	get: (url, data) => {
		return doRequest({
			url: url,
			method: 'get',
			data: data
		});
	},
	post: (url, data) => {
		return doRequest({
			url: url,
			method: 'post',
			data: data
		});
	},
	put: (url, data) => {
		return doRequest({
			url: url,
			method: 'put',
			data: data
		});
	},
	delete: (url, data) => {
		return doRequest({
			url: url,
			method: 'delete',
			data: data
		});
	}
};

module.exports = {
	request
}